package com.sinux.generality.basesupport.utils.tool;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;

public class Udp {
	private int port;
	private String groupIp;
	private DatagramSocket ds;
	private MulticastSocket ms;
	private InetAddress gr;
	public Udp(int port){
		try {
			this.ds = new DatagramSocket(port);
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}
	
	public Udp(int port, String groupIp){
		try{
			this.port = port;
			this.groupIp = groupIp;
			this.ms = new MulticastSocket();
			this.gr = InetAddress.getByName(groupIp);
			this.ms.joinGroup(gr);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public void send(byte[] bys){
		System.out.println(bys.length);
		DatagramPacket packet = new DatagramPacket(bys, bys.length, gr, port);
		try{
			if(ds != null){
				this.ds.send(packet);
			}else{
				this.ms.send(packet);
			}
		}catch(IOException e){
			e.printStackTrace();
		}
	}
	
	public void close(){
		if(ds != null){
			ds.close();
		}
		if(ms != null){
			ms.close();
		}
	}
}
